package com.tianqingwl.gsystem.security.service;

import com.tianqingwl.gsystem.security.exception.AuthenticationErrorException;
import com.tianqingwl.gsystem.resources.mapper.SysPermissionMapper;
import com.tianqingwl.gsystem.resources.pojo.SysPermission;
import com.tianqingwl.gsystem.sysuser.mapper.SysUserMapper;
import com.tianqingwl.gsystem.sysuser.pojo.SysUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.util.StringUtils;

import java.util.*;

@Configuration
public class SysUserDetailService implements UserDetailsService {

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private SysPermissionMapper sysPermissionMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws AuthenticationException {
        if (StringUtils.isEmpty(username)){
            throw new AuthenticationErrorException("用户名不能为空！");
        }
        SysUser user = sysUserMapper.findSysUserByUsername(username);
        if (user==null){
            throw new UsernameNotFoundException("用户名输入有误！");
        }
        List<SysPermission> userPermissions = sysPermissionMapper.findUserRolePermissionByUsername(username);
        List<GrantedAuthority> authorities = new ArrayList<>();

        for (SysPermission userPermission : userPermissions) {
            SimpleGrantedAuthority authority = new SimpleGrantedAuthority(userPermission.getPerFlag());
            authorities.add(authority);
        }
        user.setAuthorities(authorities);
        return user;
    }


}
